package com.sky.controller.admin;

import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;

/*
* 菜品管理
* */
@RestController
@Slf4j
@RequestMapping("/admin/dish")
public class DishController {

    @Autowired
    private DishService dishService;

    @Autowired
    private RedisTemplate redisTemplate;

    /*
    * 添加菜品
    * */
    @PostMapping
    public Result<String> save(@RequestBody DishDTO dishDTO){
        log.info("新增菜品信息：{}",dishDTO);
        dishService.save(dishDTO);
        // 清理接收到的分类id的redis缓存
        deleteRedisCache("dish_cid:"+dishDTO.getCategoryId());
        return Result.success();
    }

    /*
    * 菜品分页查询
    * */
    @GetMapping("/page")
    public Result<PageResult> pageQuery(DishPageQueryDTO dishPageQueryDTO){
        log.info("菜品分页查询：{}",dishPageQueryDTO);
        PageResult page =dishService.pageQuery(dishPageQueryDTO);
        return Result.success(page);
    }

    /*
    * 根据id查询菜品
    * */
    @GetMapping("/{id}")
    public Result<DishVO> getById(@PathVariable Long id){
        log.info("根据id查询菜品：{}",id);
        DishVO dishVO = dishService.getByIdWithFlavor(id);
        return Result.success(dishVO);
    }

    /*
    * 删除菜品
    * */
    @DeleteMapping
    public Result<String> deleteById(@RequestParam List<Long> ids){
        log.info("删除菜品：{}",ids);
        dishService.deleteByIds(ids);

        // 清理所有的菜品redis缓存
        deleteRedisCache("dish_cid:*");
        return Result.success();
    }

    /*
    * 修改菜品
    * */
    @PutMapping
    public Result<String> update(@RequestBody DishDTO dshDTO){
        log.info("修改菜品：{}",dshDTO);
        dishService.update(dshDTO);

        // 清理所有的菜品redis缓存
        deleteRedisCache("dish_cid:*");
        return Result.success();
    }

    /*
    * 修改菜品状态
    * */
    @PostMapping("/status/{status}")
    public Result<String> updateStatus(@PathVariable Integer status,Long id){
        log.info("修改菜品状态：{}",status);
        dishService.UpdateStatus(status,id);

        // 清理所有的菜品redis缓存
        deleteRedisCache("dish_cid:*");
        return Result.success();
    }

    /*
    * 清理redis缓存
    * */
    private void deleteRedisCache(String pattern){
        // 获取所有匹配的key
        Set keys = redisTemplate.keys(pattern);
        redisTemplate.delete(keys);
    }
}
